
var yerslot = 0;
var datafiles = new Array("file01.dat", "file02.dat", "file03.dat", "file04.dat", "file05.dat", "file06.dat", "file07.dat", "file08.dat", "file09.dat", "file10.dat");

function LoadGameMenu(savingorloading)
{
	if (savingorloading == undefined) savingorloading = "load";
	
	var selected = 1;	
	var ybot = 8;
	var win1h = .1*(GetScreenHeight()-8*ybot);
	var win234h = .3*(GetScreenHeight()-8*ybot);

	var win1y = ybot;
	var win2y = 3*ybot + win1h + 1;
	var win3y = ybot*5 + win1h + win234h + 1;
	var win4y = ybot*7 + win1h + win234h*2 + 1;
		//everything got screwed by the windowstyle change... so DIE
	ApplyColorMask(Black);
	var finger = LoadImage("thefinger.png");
	
	var data = new Array();
	var empties = new Array();	//can be changed by ERASING
	var slotgroups = new Array();
	var health = new Array();
	var times = new Array();
	var levels = new Array();
	var locales = new Array();
	var stages = new Array();
	var spritesets = new Array();
	var windows = {};
	
	var GetWindow = function(filename)
	{
		if (filename == undefined)
			return LoadWindowStyle('reddishfetish.rws');
		if (!(filename in windows))
			windows[filename] = LoadWindowStyle(filename);    
		return windows[filename];
	}
	
	//load the ten games
	for (var t=0; t<datafiles.length; t++)
		data[t] = OpenFile(datafiles[t]);

	for (var r=0; r<data.length; r++)
	{
		empties[r] = data[r].read("empty", "Empty");
		if (empties[r] != "Empty")
		{
			slotgroups[r] = data[r].read("party","").split(",");
			times[r] = data[r].read("time","");
			levels[r] = data[r].read(slotgroups[r][0],"").split(",")[1];
			if (levels[r] < 10) levels[r] = "0" + levels[r];
			health[r] = data[r].read(slotgroups[r][0],"").split(",")[2];
			if (health[r]) health[r] += "/" + data[r].read(slotgroups[r][0],"").split(',')[3];
			stages[r] = data[r].read("stage", "?");
			windows[r] = data[r].read("windowstyle", "reddishfetish.rws");
			locales[r] = data[r].read("dispTown","");
			if (locales[r]=="0") locales[r] = false;
			else if (locales[r]=="") locales[r] = data[r].read("mpa","");
			
			if (locales[r].length > 25)
			{
				//shorten the suckahs
				for (var u=0; u<6; u++)
				{
					if (locales[r].charAt(24+u) == " ")
					{locales[r] = locales[r].substr(0,24+u) + ".."; break;}
					else if (locales[r].charAt(24-u) == " ")
					{locales[r] = locales[r].substr(0,24-u) + ".."; break;}
					if (u==5) locales[r] = locales[r].substr(0,25) + "..";
				}
			}
		}
		delete data[r];	//close em.
	}

	var text_height = font.getHeight();
	while (AreKeysLeft()) GetKey();
		
	var redraw = true;
	var thatop = 0;
	var MENUDUH = 0;
	
	do{

	if (redraw)
	{		//DRAW THE MENU
		var wid = GetScreenWidth();
		window.drawWindow(xbo, win1y, wid-xbo*2, win1h);
		alphagrad.transformBlit(7,ybo-3,	    wid-xbo+3,ybo-3,  319-xbo+3, win1y+20,  xbo-3, win1y+20);
		font.setColorMask(White);
		font.drawText(wid/2-font.getStringWidth("New Game")/2,ybo, (savingorloading=="load") ? "New Game" : "Save Game");

		// CUSTOMIZED WINDOWS!
		GetWindow(windows[thatop]).drawWindow(xbo, win2y, wid-xbo*2, win234h);
		alphagrad.transformBlit(7,win2y-3,  wid-xbo+3,win2y-3,  319-xbo+3, win2y+55,  xbo-3, win2y+55);
		
		GetWindow(windows[thatop+1]).drawWindow(xbo, win3y, wid-xbo*2, win234h);
		alphagrad.transformBlit(7,win3y-3,  wid-xbo+3,win3y-3,  319-xbo+3, win3y+55,  xbo-3, win3y+55);
		
		GetWindow(windows[thatop+2]).drawWindow(xbo, win4y, wid-xbo*2, win234h);
		alphagrad.transformBlit(7,win4y-3,  wid-xbo+3,win4y-3,  319-xbo+3, win4y+55,  xbo-3, win4y+55);
		
			
			
		for (var thislot=thatop; thislot<thatop+3; thislot++)
		{
			font.drawText((GetScreenWidth()-xbo-font.getStringWidth(thislot+1)), eval('win'+(thislot+2-thatop)+'y')+win234h/2-25, thislot+1);
			if (empties[thislot] != "Empty")
			{
			font.drawText(xbo+5,eval('win'+(thislot+2-thatop)+'y')+win234h/2-18,slotgroups[thislot][0]);
			font.drawText(xbo+5,eval('win'+(thislot+2-thatop)+'y')+win234h/2-12+text_height*2,times[thislot].substr(0,5));
			if (levels[thislot]) font.drawText(GetScreenWidth()-xbo-font.getStringWidth(levels[thislot]),eval('win'+(thislot+2-thatop)+'y')+win234h/2-12+text_height,levels[thislot]);
			if (health[thislot]) font.drawText(GetScreenWidth()-xbo-font.getStringWidth(health[thislot]),eval('win'+(thislot+2-thatop)+'y')+win234h/2-12+text_height*2,health[thislot]);
			
			//draws the sprites of party
			for (var thischa=0; thischa<slotgroups[thislot].length; thischa++)
			{
				if (spritesets[slotgroups[thislot][thischa]]==undefined)	//load same char's ss once
					spritesets[slotgroups[thislot][thischa]] = LoadSpriteset(charstats[slotgroups[thislot][thischa]].rss);
				for (var r10=0; r10<spritesets[slotgroups[thislot][thischa]].directions.length; r10++)
					if (spritesets[slotgroups[thislot][thischa]].directions[r10].name == "west")
					spritesets[slotgroups[thislot][thischa]].images[  spritesets[slotgroups[thislot][thischa]].directions[r10].frames[0].index  ].blit(GetScreenWidth()/2-20*slotgroups[thislot].length/2+thischa*20-6, eval('win'+(thislot+2-thatop)+'y')+win234h/2-20);
				
			}
			if (locales[thislot]) font.drawText(GetScreenWidth()/2-font.getStringWidth(locales[thislot])/2, eval('win'+(thislot+2-thatop)+'y')+win234h/2-15+text_height*2, locales[thislot]);
			font.drawText(GetScreenWidth()/2-font.getStringWidth(stages[thislot])/2, eval('win'+(thislot+2-thatop)+'y')+win234h/2-5+text_height*2, stages[thislot]);
			font.setColorMask(Cyan);
			font.drawText(xbo+5,eval('win'+(thislot+2-thatop)+'y')+win234h/2-12+text_height,"Time");
			var lvwidth = font.getStringWidth("Lv "+levels[thislot]);
			font.drawText(GetScreenWidth()-xbo-((levels[thislot]==undefined) ? 38 : lvwidth), eval('win'+(thislot+2-thatop)+'y')+win234h/2-12+text_height, "Lv ");
			font.setColorMask(White);
			}
			else
				font.drawText(xbo+5,eval('win'+eval(thislot+2-thatop)+'y')+win234h/2-18,"Empty");
		}
		MENUDUH = GrabImage(0,0,GetScreenWidth(),GetScreenHeight());
		redraw = false;
	}
		
	
		MENUDUH.blit(0,0);
		finger.blit(0, eval("win" + selected+ "y"));
		FlipScreen();		

		switch (GetKey())
		{
			case key_cancel:
			{
				if (thempa != "blank.rmp") return;
				break;
			}
			case KEY_DOWN:
			{
				if (selected != 4){ selected++; curse.stop(); curse.play(false); }
				else if (thatop != 7){ thatop++; redraw=true; curse.stop(); curse.play(false); }
				break;
			}
			case KEY_UP:
			{
				if (selected == 2 && thatop != 0){ thatop--; redraw=true; curse.stop(); curse.play(false); }
				else if (selected != 1){ selected--; curse.stop(); curse.play(false); }
				break;
			}
			case key_talk:
			{
				var yerslot = selected-2+thatop;
				if (savingorloading=="load")
				{
					if (empties[yerslot] != "Empty")
					{
						curse.stop(); curse.play(false);
						//confirm menu
						while (AreKeysLeft()) GetKey();
						MENUDUH.blit(0,0);
						finger.blit(0, eval("win" + selected+ "y"));
						var yeanay = 110;
						var stop = (thempa=="blank.rmp" && !eventBox['splits'].inprog);
						window.drawWindow(80, 100, 120, 30);
						alphagrad.transformBlit(80+120+rfXo,100+30+rfYo,  80-rfXo,100+30+rfYo,  80-rfXo,100-rfYo,  80+120+rfXo,100-rfYo);
						font.drawText(90,100, "Confirm.");
						font.drawText(100,110, "False.");
						font.drawText(100,120, "Load.");
						var hugecrap = GrabImage(0,0,GetScreenWidth(), GetScreenHeight());
						while (!stop && !IsKeyPressed(key_cancel))
						{
							hugecrap.blit(0,0);
							finger.blit(80,yeanay);
							FlipScreen();
							switch (GetKey())
							{
								case KEY_UP: {yeanay = 110; break;}
								case KEY_DOWN: {yeanay = 120; break;}
								case key_talk: {stop = true; break;}
							}
						}
						if (stop && (yeanay==120 || (thempa=="blank.rmp" && !eventBox['splits'].inprog)))	//stop: false if confirm-menu cancelled w/BACK
						{
							ApplyColorMask(Black);
							fadecol[3] = 255;
							font.drawText(15,15,"LOADING...");
							FlipScreen();
							if (selected==1) StartGame();
							else LoadTheGameAlready(yerslot);
							return;
						}
					}
					break;
				}
				else if (savingorloading=="save")
				{
					if (selected == 1)
					{
						break;	//the topmost box isn't a save slot ... do nothing
					}
					else
					{
						if (empties[selected+thatop-2]!="Empty" && selected!=1)
						{
							while (AreKeysLeft()) GetKey();
							MENUDUH.blit(0,0);
							finger.blit(0, eval("win" + selected+ "y"));
							var yeanay = 110;
							var stop = false;
							window.drawWindow(80, 100, 120, 30);
							alphagrad.transformBlit(80+120+rfXo,100+30+rfYo,  80-rfXo,100+30+rfYo,  80-rfXo,100-rfYo,  80+120+rfXo,100-rfYo);
							font.drawText(90,100, "Overwrite?");
							font.drawText(100,110, "No.");
							font.drawText(100,120, "I'm serious.");
							var hugecrap = GrabImage(0,0,GetScreenWidth(), GetScreenHeight());
							while ((!stop || !IsKeyPressed(key_talk)) && !IsKeyPressed(key_cancel))
							{
								hugecrap.blit(0,0);
								finger.blit(80,yeanay);
								FlipScreen();
								switch (GetKey())
								{
									case KEY_UP: {yeanay = 110; break;}
									case KEY_DOWN: {yeanay = 120; break;}
									case key_talk: {stop = true; break;}
								}
							}
						}
						if (stop && yeanay==120 || empties[selected+thatop-2]=="Empty")
						{
							ApplyColorMask(Black);
							font.drawText(15,15,"SAVING...");
							FlipScreen();
							savegame(yerslot);
							//LoadGameMenu("save");	//redisplay the info
							return;
						}
					break;
					}
					
				}
				else {}	//something crazy happened!!!
				break;
				
			}
			case KEY_DELETE:
			{
				if (empties[selected+thatop-2]!="Empty" && selected!=1)
				{
					MENUDUH.blit(0,0);
					finger.blit(0, eval("win" + selected+ "y"));
					var yeanay = 110;
					var infin = true;
					window.drawWindow(80, 100, 120, 30);
					alphagrad.transformBlit(80+120+rfXo,100+30+rfYo,  80-rfXo,100+30+rfYo,  80-rfXo,100-rfYo,  80+120+rfXo,100-rfYo);
					font.drawText(90,100, "ERASE fo' real?");
					font.drawText(100,110, "No_ Never.");
					font.drawText(100,120, "Definitely!");
					var hugecrap = GrabImage(0,0,GetScreenWidth(), GetScreenHeight());
					while (!IsKeyPressed(key_talk) && infin)
					{
						hugecrap.blit(0,0);
						finger.blit(80,yeanay);
						FlipScreen();
						switch (GetKey())
						{
							case KEY_UP: {yeanay = 110; break;}
							case KEY_DOWN: {yeanay = 120; break;}
							case key_cancel: {infin = false; break;}
						}
					}
					if (yeanay==120 && infin)
					{
						yerslot = selected-2+thatop;
					//	Abort(yerslot);
						empties[yerslot] = ERASEgame(yerslot);
						redraw = true;
					}
				}
			}
			break;
		}
	}while (true)
}




function LoadTheGameAlready(filthyslot)
{
	while (AreKeysLeft()) GetKey();	//DEVOUR the keys!!
	var stuff = OpenFile(datafiles[filthyslot]);
	party = stuff.read("party", "").split(",");
	var fools = GetPersonList();
	for (var d=0; d<fools.length; d++)
		DestroyPerson(fools[d]);					//kill everyone
	thePC = new retard(party[0], charstats[party[0]].rss, false);
	for (var f=0; f<theHUGEeventlist.length; f++)
		eventBox[theHUGEeventlist[f]].inprog = false;	//stop all events
	var inprogger = stuff.read('inprog', 'yeuh!');
	if (inprogger!='none') eventBox[inprogger].inprog = true;	//restore cur.event status
	var thenerds = stuff.read("events", []).split(",");
	for (var l=0; l<theHUGEeventlist.length; l++)
		eventBox[theHUGEeventlist[l]].happened = eval(thenerds[l]);
	saveable = stuff.read("saveable", true);
	fanceydisplay = stuff.read("fanceydisp", true);
	windowstyle = stuff.read("windowstyle", "?");
	window = LoadWindowStyle(windowstyle);
	var timeunits = stuff.read("time", "").split(":");
	originaltime = timeunits[0]*3600000 + timeunits[1]*60000 + timeunits[2]*1000;
	evillaughs = stuff.read("laughs", 0);
	money = stuff.read("cash", 0);
	stage = stuff.read("stage", "?");
	thecouch = stuff.read("thecouch", 0);
	var couches = stuff.read("thecouches", []).split(",");
		COUCH2=eval(couches[0]), COUCH2UP=eval(couches[1]), COUCH3=eval(couches[2]), COUCH3UP=eval(couches[3]), COUCHM=eval(couches[4]);
	thefridge = stuff.read("thefridge", 0);
	var fridges = stuff.read("thefridges", []).split(",");
		FRIDGE2UP=eval(fridges[0]), FRIDGE3=eval(fridges[1]), FRIDGEM=eval(fridges[2]);
	thetele = stuff.read("thetele", 0);
	var teles = stuff.read("theteles", []).split(",");;
		TELE2=eval(teles[0]), TELE3=eval(teles[1]), TELE3UP=eval(teles[2]), TELEM=eval(teles[3]);
	chests = stuff.read("chests", []).split(",");
	for (var g=0; g<chests.length; g++)		//booleate the array 
		chests[g] = (eval(chests[g])) ? 1 : 0;
		
	for (var i=0; i<party.length; i++)
	{		//restore saved stats
		var dudejunk = stuff.read(party[i], "").split(",");
		charstats[party[i]][statlist[0]] = dudejunk[0];	//name
		for (var j=1; j<=15; j++)
			charstats[party[i]][statlist[j]] = dudejunk[j]*1;	//stats = numbers
		charstats[party[i]].rss = dudejunk[16];
		charstats[party[i]].facepic = (dudejunk[17] && dudejunk[17]!="undefined" && dudejunk[17]!="") ?dudejunk[17] : undefined;
		charstats[party[i]].rhand = (dudejunk[18] && dudejunk[18]!="undefined" && dudejunk[18]!="") ? weapons[dudejunk[18]].obj_id : undefined;
		charstats[party[i]].lhand = (dudejunk[19] && dudejunk[19]!="undefined" && dudejunk[19]!="") ? weapons[dudejunk[19]].obj_id : undefined;
		charstats[party[i]].head = (dudejunk[20] && dudejunk[20]!="undefined" && dudejunk[20]!="") ? weapons[dudejunk[20]].obj_id : undefined;
		charstats[party[i]].body = (dudejunk[21] && dudejunk[21]!="undefined" && dudejunk[21]!="") ? weapons[dudejunk[21]].obj_id : undefined;
		charstats[party[i]].relic1 = (dudejunk[22] && dudejunk[22]!="undefined" && dudejunk[22]!="") ? weapons[dudejunk[22]].obj_id : undefined;
		charstats[party[i]].relic2 = (dudejunk[23] && dudejunk[23]!="undefined" && dudejunk[23]!="") ? weapons[dudejunk[23]].obj_id : undefined;
	  charspells[party[i]] = stuff.read(party[i] + "spells", "").split(",");
		//charstats[party[i]].status = dudejunk[24];
	}
	
	charshards = stuff.read("charshards", "").split(",");
	
	for (j=0; j<itemlist.length; j++)
	{
		var ehhh = stuff.read("item:" + itemlist[j], "").split(",");
		items[itemlist[j]].quantity = ehhh[0]*1;
		items[itemlist[j]].order = ehhh[1]*1;
	}

	key_talk = stuff.read("key_talk", 67);
	key_cancel = stuff.read("key_cancel", 27);
	key_menu = stuff.read("key_menu", 70);
	key_laugh = stuff.read("key_laugh", 58);
	key_debug = stuff.read("key_debug", 65);
	key_shoes = stuff.read("key_shoes", 62);
	SetMapEngineFrameRate(stuff.read("fpschoice", 45));
	stuff.flush();
	eventinprog = false;
	eventmark=0;
	initGame();	//dont call map_init after initGame
	thempa = stuff.read("mpa","");
	ChangeMap(thempa);
	people = GetPersonList();
	SetPersonX(thePC.name, stuff.read("poX",25));
	SetPersonY(thePC.name, stuff.read("poY",25));
	SetPersonLayer(thePC.name, stuff.read("poL", 1));
	stairdir = 0;
	bgmswitch(getmapbgm(thempa), true, true);
	
	fadeInScreen();
	//battle(randomgroup());
	//mainmenu();
}




function savegame(dirtyslot)
{
	var savesfx = LoadSound("save_sfx.wav");
	var thejunk = OpenFile(datafiles[dirtyslot]);
	thempa = GetCurrentMap();
	thejunk.write("mpa", thempa);
	thejunk.write("poX", GetPersonX(thePC.name));
	thejunk.write("poY", GetPersonY(thePC.name));
	thejunk.write("poL", GetPersonLayer(thePC.name));
	thejunk.write("debugable", debugable);
	thejunk.write("saveable", saveable);
	thejunk.write("fanceydisp", fanceydisplay);
	thejunk.write("windowstyle", windowstyle);
	thejunk.write("empty", "no");
	thejunk.write("time", timer.getTime());
	thejunk.write("party", party);
	for (var i=0; i<charlist.length; i++)
	{
		var listostats = "";
		for (j=0; j<statlist.length; j++)
			listostats += charstats[charlist[i]][statlist[j]] + ((j<statlist.length-1) ? "," : "");
		thejunk.write(charlist[i], listostats);
		thejunk.write(charlist[i] + "spells", charspells[charlist[i]]);	
	}
	
	thejunk.write("charshards", charshards);
	
	thejunk.write("laughs", evillaughs);
	thejunk.write("cash", money);
	thejunk.write("dispTown", dispTownsave);
	thejunk.write("stage", stage);
	thejunk.write("thecouch", thecouch);
	thejunk.write("thecouches", [COUCH2, COUCH2UP, COUCH3, COUCH3UP, COUCHM]);
	thejunk.write("thefridge", thefridge);
	thejunk.write("thefridges", [FRIDGE2UP, FRIDGE3, FRIDGEM]);
	thejunk.write("thetele", thetele);
	thejunk.write("theteles", [TELE2, TELE3, TELE3UP, TELEM]);
	thejunk.write("chests", chests);
	
	for (var r=0; r<itemlist.length; r++)
		thejunk.write("item:" + itemlist[r], items[itemlist[r]].quantity + "," + items[itemlist[r]].order);
	
	var noevent = true;
	var agadabwus = new Array();
	for (var l=0; l<theHUGEeventlist.length; l++)
	{
		agadabwus[l] = eventBox[theHUGEeventlist[l]].happened;
		if (eventBox[theHUGEeventlist[l]].inprog && noevent){ thejunk.write('inprog', theHUGEeventlist[l]); noevent=false; }
	}
	thejunk.write("events", agadabwus);
	if (noevent) thejunk.write('inprog', 'none');
	thejunk.write("key_talk", key_talk);
	thejunk.write("key_cancel", key_cancel);
	thejunk.write("key_menu", key_menu);
	thejunk.write("key_laugh", key_laugh);
	thejunk.write("key_debug", key_debug);
	thejunk.write("key_shoes", key_shoes);
	thejunk.write("fpschoice", fpschoice);
	thejunk.flush();
	savesfx.play(false);
}


function ERASEgame(yerslotty)
{
	//some funny sound  var savesfx = LoadSound("save_sfx.wav");
	//for some reason global yerslot was zero here
	var goner = OpenFile(datafiles[yerslotty]);
	goner.write("mpa", "");
	goner.write("poX", "");
	goner.write("poY", "");
	goner.write("debugable", "");
	goner.write("empty", "Empty");
	goner.write("time", "");
	goner.write("party", "");
	goner.write("levels", "");
	goner.write("health", "");
	goner.write("magic", "");
	goner.write("laughs", "");
	goner.write("cash", "");
	
	for (r=0; r<itemlist.length; r++)
	{
		goner.write("item:" + itemlist[r], "0,0");
	}
	
	goner.write("key_talk", KEY_ENTER);
	goner.write("key_cancel", KEY_BACKSPACE);
	goner.write("key_menu", KEY_HOME);
	goner.write("key_laugh", KEY_SPACE);
	goner.write("key_debug", KEY_SLASH);
	goner.write("key_shoes", KEY_SHIFT);
	//goner.write("windowstyle", "reddishfetish.rws");
	
	goner.flush();
	//savesfx.play(false);
	return "Empty";
}
